package org.blindmandesign;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.generic.SafeConfig;
import org.apache.velocity.tools.generic.ValueParser;

/**
 * <p>
 * <pre>
 * Example uses in a template:
 *   #set( $foospan = $jQ.span.id($foo.id).body($foo) )
 *   $jQ.mark('table tr.bar td').body("This is $foospan")
 *
 * Output:
 *   <table>
 *     <tr class="bar">
 *       <td>This is <span id="foo1">my first foo.</span></td>
 *     </tr>
 *   </table>
 *
 *
 * Example tools.xml config:
 * &lt;tools&gt;
 *   &lt;toolbox scope="application"&gt;
 *     &lt;tool class="org.blindmandesign.Tool"/&gt;
 *   &lt;/toolbox&gt;
 * &lt;/tools&gt;
 * </pre></p>
 *
 * @author Nathan Bubna
 * @since javaQuery 1.0
 * @version $Id$
 */
@DefaultKey("jQ")
public class Tool extends SafeConfig {

    public static final String TAB_KEY = "tab";
    public static final String DELIMITER_KEY = "delimiter";
    public static final String PARSER_KEY = "parser";
    private Config config = new Config();
    private Parser parser;

    protected void configure(ValueParser cfg) {
        String tab = cfg.getString(TAB_KEY);
        if (tab != null) {
            config.setTab(tab);
        }
        String delim = cfg.getString(DELIMITER_KEY);
        if (delim != null) {
            config.setDelimiter(delim);
        }
        //TODO: configurable parser class
        //Class cls = cfg.getClass(PARSER_KEY);
        parser = new SelectorParser(config);
        config.setParser(parser);

        boolean lock = cfg.getBoolean(LOCK_CONFIG_KEY, true);
        config.lock(lock);
    }

    public Config getConfig() {
        return config;
    }

    public jQ get(String tag) {
        return mark(tag);
    }

    public jQ mark(String definition) {
        try {
            return new jQ(definition, parser);
        }
        catch (Exception e) {
            //TODO: log this
            return null;
        }
    }

    protected List parse(String definition) throws Exception {
        return parser.parse(definition);
    }

}
